#!/user/bin/env python
# -*- coding: utf-8 -*-

from utils import log

from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, Integer, UnicodeText, desc, asc
from sqlalchemy.sql.sqltypes import TIMESTAMP
from sqlalchemy.sql import func
from data_pool_mysql import engine

Session = sessionmaker()
Session.configure(bind=engine)

""" topic_gallery_item collection has
    id:             自增id
    provid:         话题省份（int）
    gtype:          类型（int）
    seq:            次序（int）
    remark:         备注（str)
    ctime:          话题创建时间（datetime）
"""
metadata = MetaData()

TOPIC_GALLERY_TYPE_RECOMMEND, TOPIC_GALLERY_TYPE_COMMON_HOT,\
    TOPIC_GALLERY_TYPE_PROV_HOT, TOPIC_GALLERY_TYPE_RANDOM = range(4)

class TopicGalleryItem(object):
    """docstring for TopicTitleItem"""

    def to_dict(self):
        res = {}
        res['provid'] = self.provid
        res['gtype'] = self.gtype
        res['seq'] = self.seq
        res['remark'] = self.remark
        res['ctime'] = self.ctime.strftime("%Y-%m-%d %H:%M:%S")\
            if self.ctime else ""
        return res

    def __repr__(self):
        return "%d" % (self.provid)


topic_gallery_table = Table(
    'topic_gallery', metadata,
    Column('id', Integer, primary_key=True, autoincrement=True),
    Column('provid', Integer, index=True, nullable=False),
    Column('gtype', Integer, nullable=False),
    Column('seq', Integer, nullable=False),
    Column('remark', UnicodeText, nullable=True),
    Column('ctime', TIMESTAMP, server_default=func.now())
)

mapper(TopicGalleryItem, topic_gallery_table)


def create_topic_gallery_table_if_not_exist():
    metadata.create_all(engine)


def add_topic_gallery_item(p_item):
    item = TopicGalleryItem()
    item.provid = p_item['provid']
    item.gtype = p_item['gtype']
    item.seq = p_item['seq']
    item.remark = p_item['remark']
    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def del_topic_gallery_item_by_provid(p_provid):
    try:
        session = Session()
        session.query(TopicGalleryItem).filter_by(provid=p_provid).delete()
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()


def get_topic_gallery_by_provid(p_provid):
    try:
        session = Session()
        item_list = session.query(TopicGalleryItem).filter_by(provid=p_provid)\
            .order_by(asc(TopicGalleryItem.seq)).all()
        res_list = [i.to_dict() for i in item_list]
        return res_list
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()


if __name__ == "__main__":
    create_topic_gallery_table_if_not_exist()
